package com.jingge.home.framework;

import com.jingge.home.util.LocalCacheManager;
import com.jingge.home.util.wx.WxMessageBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 更多消息处理器
 *
 * @author Yongxiang
 * @date 2025-07-31 16:16
 * @email 1158055613@qq.com
 */
@Component
public class MoreMsgHandler implements WxCpMessageHandler {
	private static final String SIMPLE_MORE_MSG_COMMAND = "m";
	@Autowired
	private LocalCacheManager<String, String> msgCache;

	@Override
	public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage,
	                                Map<String, Object> context,
	                                WxCpService wxCpService,
	                                WxSessionManager sessionManager) throws WxErrorException {
		String content = wxMessage.getContent();
		String to = wxMessage.getFromUserName();
		String from = wxMessage.getToUserName();
		String recentMsgId = msgCache.getAsString(CacheKeyConstant.RECENT_MSG_ID_PREFIX + to);
		if (!SIMPLE_MORE_MSG_COMMAND.equals(content.trim())) {
			return WxMessageBuilder.buildTextMessage("错误的更多消息指令，指令应该为\"m\"。", from, to);
		}
		if (StringUtils.isEmpty(recentMsgId)) {
			return WxMessageBuilder.buildTextMessage("没有更多的消息啦", from, to);
		}
		String msg = msgCache.getAsString(recentMsgId);
		return WxMessageBuilder.buildTextMessage(StringUtils.isEmpty(msg) ? "没有更多的消息啦" : msg, from, to);
	}
}
